﻿using KingerRobot.PCRBW.Dao;
using KingerRobot.PCRMES.Spi;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.Biz;
/// <summary>
/// 异常口滑台取料验证——物料返库滑台任务
/// </summary>
public class AbnormalBiz : K8.MDCBB.Biz
{
    #region 配置参数
    private ParamData Param { get; set; }

    class ParamData
    {
        /// <summary>
        /// 机台名称
        /// </summary>
        public string EquipName { get; set; }
    }
    #endregion

    #region PLC 通讯参数
    private ValueData Data { get; set; }
    class ValueData
    {
        #region 点位

        /// <summary>
        /// 异常口滑台状态
        /// </summary>
        public int AbSlideStatus { get; set; }
        /// <summary>
        /// 异常口交互标志位
        /// </summary>
        public int AbCommandFlag { get; set; }
        /// <summary>
        /// 异常口滑台任务流水号
        /// </summary>
        public int AbSerialNumber { get; set; }
        /// <summary>
        /// 异常口滑台取圈内径
        /// </summary>
        public int AbInnerdiameter { get; set; }
        /// <summary>
        /// 异常口滑台任务指令码
        /// </summary>
        public int AbCommandCode { get; set; }
        /// <summary>
        /// 异常口滑台完成任务流水号
        /// </summary>
        public int AbReSerialNumber { get; set; }
        /// <summary>
        /// 异常口允许放料（允许龙门放料）0为不允许放，1为允许放
        /// </summary>
        public int AbAllowSignal { get; set; }
        /// <summary>
        /// 异常口有货（请求龙门取货）0为不允许取，1为允许取
        /// </summary>
        public int AbHasGoodSignal { get; set; }
        /// <summary>
        /// 人工放料请求人工入库
        /// </summary>
        public int AbManualComplete { get; set; }
        #endregion
    }
    #endregion

    #region 缓存
    private CacheData Cache { get; set; }
    class CacheData
    {
        public int FinalTaskNo { get; set; }
    }
    #endregion

    #region 实时日志
    private StepData Step { get; set; }
    class StepData
    {
        private string _msg = string.Empty;
        public string StepMsg
        {
            get
            {
                return this._msg;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this._msg = string.Empty;
                    return;
                }
                this._msg = $"{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}>>{value}";
            }
        }
    }
    private void StepMsg(string msg)
    {
        this.Step.StepMsg = msg;
        this.WriteLog(msg);
    }
    #endregion

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message)
    {
        K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
    }
    #endregion

    /// <summary>
    /// 和 PLC 通讯对象
    /// </summary>
    private BizData BizData { get; set; }
    public int Execute(BizData writer)
    {
        // Excute 方法外使用 BizParam
        this.BizData = writer;
        // 返回参数
        var result = 0;
        string errorMsg = string.Empty;

        #region 完成任务
        //完成任务
        //if (Data.AbSerialNumber > 0 && Data.AbReSerialNumber > 0 && Data.AbSerialNumber != Data.AbReSerialNumber)
        //{
        //    this.StepMsg($"龙门出入库》{Param.EquipName}龙门写流水号与反馈流水号不一致 SerialNumber-{Data.AbSerialNumber}，ReSerialNumber-{Data.AbReSerialNumber}");
        //    return 0;
        //}  
        if (Data.AbSerialNumber > 0 && Data.AbHasGoodSignal==1 && Data.AbSerialNumber != Cache.FinalTaskNo)
        {
            FinishTask(writer);
            return result;
        }
        #endregion

        if (Data.AbSlideStatus != (int)EnumGantryStatus.Free)
        {
            this.StepMsg($"异常滑台》{Param.EquipName}号滑台不可写或非空闲状态 GantryStatus-{Data.AbSlideStatus}");
            return result;
        }
        if (Data.AbCommandFlag != (int)EnumGantryStatus.Free)
        {
            this.StepMsg($"异常滑台》{Param.EquipName}号滑台交互位空闲状态 GantryStatus-{Data.AbCommandFlag}");
            return result;
        }
        if (Data.AbManualComplete !=1)
        {
            this.StepMsg($"异常滑台》{Param.EquipName}号滑台交互位空闲状态 GantryStatus-{Data.AbCommandFlag}");
            return result;
        }

        var service = K8.RSF.Client.Create<ISlibeTableService>();
        var task = service.CreateTask(Param.EquipName,2);
        if (task==null || task.TaskNo==-1)
        {
            this.StepMsg($"异常滑台》{Param.EquipName}未创建任务！返回值null");
            return result;
        }
        this.StepMsg($"异常滑台》日志1,返回值:{task.TaskNo}");
        if (task.TaskNo <= 0)
        {
            this.StepMsg($"异常滑台》{Param.EquipName}未创建任务！返回值{task.TaskNo}");
            return result;
        }
       
        //取料信号传递给滑台 取料  //下发流水号
        var data = this.BizData.WriteData(new
        {
            AbSerialNumber = task.TaskNo,//任务流水号
            AbInnerdiameter = task.Innerdiameter,//尺寸
            AbCommandCode=1,
            AbCommandFlag =1
        });
        data = this.BizData.WriteData(new
        {
            AbCommandFlag = 1
        });
        if (data > 0)
        {
            //指令下发取料成功
            this.StepMsg($"异常滑台》滑台{Param.EquipName}指令下发取料成功:{data}");
            int flag = service.ExecuteTask(task.TaskNo, 0);
            if (flag <= 0)
            {
                this.StepMsg($"异常滑台》{Param.EquipName}未下发执行任务！返回值{flag}，任务号：{task.TaskNo}");
                return result;
            }
           
        }
        else
        {
            this.StepMsg($"异常滑台{Param.EquipName}指令下发取料失败！");
        }

        return result;
    }
    private void FinishTask(BizData writer)
    {
        var taskService = K8.RSF.Client.Create<ISlibeTableService>();
        var finishResult = taskService.FinishTask(Data.AbSerialNumber);
        if (finishResult == 1)
        {
            Cache.FinalTaskNo = Data.AbReSerialNumber;//流水号缓存
            this.StepMsg($"滑台入库》[{Param.EquipName}]滑台,完成任务结束");
        }
    }
}
